package org.example.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import org.apache.ibatis.annotations.Mapper;
import org.example.R.R;
import org.example.constants.CoreConstants;
import org.example.entity.dto.*;
import org.example.entity.po.UserPO;
import org.example.entity.vo.admin.AddDyTaskDto;
import org.example.entity.vo.admin.DyUserVO;
import org.example.entity.vo.admin.UserVO;
import org.example.mapper.UserMapper;
import org.example.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;

    public R login(LoginUserDto dto) {

        UserVO userVO = userMapper.selectUserByUserName(dto.getUsername());
        if (userVO == null) {
            return R.error("该用户不存在");
        }
        String password = SaSecureUtil.aesDecrypt(CoreConstants.key, userVO.getPassword());
        if (!password.equals(dto.getPassword())) {
            return R.error("密码错误");
        }
        StpUtil.login(userVO.getId());

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        Map<String, Object> voMap = new HashMap<>();
        voMap.put("token", tokenInfo);
        voMap.put("userId", userVO.getId());
        voMap.put("status", userVO.getStatus());


        return R.success("登录成功").setData(voMap);
    }

    public R add(AddUserDto dto) {
        UserVO userVO = userMapper.selectUserByUserName(dto.getUsername());
        if (userVO != null) {
            return R.error("该账号已存在");
        }

        if (dto.getPassword().length() < 8) {
            return R.error("密码不得少于8位");
        }

        UserPO po = new UserPO();
        BeanUtils.copyProperties(dto, po);
        po.setId(IdUtil.getSnowflakeNextId());
        po.setNickname("新用户");
        String encryptPassword = SaSecureUtil.aesEncrypt(CoreConstants.key, po.getPassword());
        po.setPassword(encryptPassword);
        po.setStatus(111);
        po.setCreateTime(TimeUtils.getCurrentDate());


        userMapper.insert(po);

        return R.success("注册成功");
    }

    public R detail(Long userId) {
        UserVO userVO = userMapper.selectUserById(userId);
        return R.success("获取成功").setData(userVO);
    }

    public R save(SaveUserDto dto) {
        UserVO userVO = userMapper.selectUserById(Long.valueOf(dto.getUserId()));
        if (userVO == null) {
            return R.error("该用户不存在");
        }
        userMapper.update(dto);
        return R.success("保存成功");
    }

    public R updatePassword(SavePasswordDto dto) {
        UserVO userVO = userMapper.selectUserById(Long.valueOf(dto.getUserId()));
        if (userVO == null) {
            return R.error("该用户不存在");
        }
        String encryptPassword = SaSecureUtil.aesEncrypt(CoreConstants.key, dto.getPassword());
        userMapper.updatePassword(encryptPassword, userVO.getId());
        return R.success("密码修改成功");
    }

    public R isLogin(String tokenValue) {
        Object token = StpUtil.getLoginIdByToken(tokenValue);
        if (token == null) {
            return R.error("未登录");
        }
        return R.success("已登录");
    }

    public R list() {
        List<UserVO> list = userMapper.list();
        list.sort(Comparator.comparing(UserVO::getCreateTime).reversed());
        return R.success("获取成功").setData(list);
    }

    public R delete(Long userId) {
        userMapper.delete(userId);
        return R.success("删除成功");
    }

    public R modifyRole(ModifyRoleDto dto) {
        UserVO userVO = userMapper.selectUserById(Long.valueOf(dto.getId()));
        if (userVO == null) {
            return R.error("该用户不存在");
        }
        userMapper.modifyRole(dto);
        return R.success("保存成功!");
    }

    public R dyList() {
        List<DyUserVO> result = new ArrayList<>();
        List<UserVO> list = userMapper.list();
        List<UserVO> userList = list.stream().filter(v -> v.getStatus() == 222).collect(Collectors.toList());
        userList.forEach(obj -> {
            DyUserVO vo = new DyUserVO();
            vo.setLabel(obj.getNickname());
            vo.setValue(String.valueOf(obj.getId()));
            result.add(vo);
        });
        return R.success("获取成功").setData(result);
    }

    public R assTask(AddDyTaskDto dto) {
        userMapper.assTask(dto);
        return R.success("任务分配成功");
    }
}
